// src/store/index.js
import { defineStore } from 'pinia'

export const useWineStore = defineStore('wine', {
  state: () => ({
    featuredGoods: [],
    products: [],
    users: [
      {
        id: 1,
        username: 'admin',
        email: 'admin@wineshop.com',
        role: '管理员',
        registerDate: '2024-01-15'
      },
      {
        id: 2,
        username: 'user001',
        email: 'user001@example.com',
        role: '普通用户',
        registerDate: '2024-02-20'
      }
    ],
    searchResults: []
  }),

  getters: {
    getProductById: state => id => {
      return state.products.find(product => product.id === id)
    },
    getProductsByType: state => type => {
      return state.products.filter(product => product.type === type)
    },
    getUserById: state => id => {
      return state.users.find(user => user.id === id)
    }
  },

  actions: {
    setProducts(productList) {
      this.products = productList
    },
    setFeaturedGoods(list) {
      this.featuredGoods = list
    },
    addProduct(product) {
      const newProduct = {
        ...product,
        id: this.products.length + 1,
        image: product.image || `https://via.placeholder.com/200x300/8B4513/fff?text=${product.type}`
      }
      this.products.push(newProduct)
    },

    addUser(user) {
      const newUser = {
        ...user,
        id: this.users.length + 1,
        registerDate: new Date().toISOString().split('T')[0]
      }
      this.users.push(newUser)
    },

    searchProducts(query) {
      console.log('Searching for:', query)
      console.log('Current products:', this.products)
      if (!query.trim()) {
        this.searchResults = [...this.products]
        return
      }

      const lowerQuery = query.toLowerCase()
      this.searchResults = this.products.filter(product => product.name.toLowerCase().includes(lowerQuery) || product.origin.toLowerCase().includes(lowerQuery))
    },

    filterProducts(filters) {
      let results = [...this.products]

      if (filters.origin && filters.origin !== 'all') {
        results = results.filter(product => product.origin === filters.origin)
      }

      if (filters.minPrice) {
        results = results.filter(product => product.price >= filters.minPrice)
      }

      if (filters.maxPrice) {
        results = results.filter(product => product.price <= filters.maxPrice)
      }

      this.searchResults = results
    }
  }
})
